﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;
using System.Data;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
using Senparc.Weixin.QY.Entities;
using Senparc.Weixin.QY.CommonAPIs;
using Senparc.Weixin.QY.AdvancedAPIs;
using Senparc.Weixin.QY.AdvancedAPIs.OAuth2;
using Senparc.Weixin.Helpers;
using Senparc.Weixin.HttpUtility;
using System.IO;
using System.Text;
using System.Threading;
using SZHL.Data;

namespace SZHL.UI.AppCode
{
    public class WXHelp
    {

        private static string WXUrl = "";// WXHelp.GetWXInfo("WXUrl");

        //public static string corpId = WXHelp.GetWXInfo("corpId");
        //public static string corpId = "wxf285796b249c0cf6";
        public static string corpId = "";//"wx102a8aac04b33c39";//
        //public static string corpSecret = WXHelp.GetWXInfo("corpSecret");
        //public static string corpSecret = "0XSmLBYtwGg0W1lDnYA2cdY_GxA1e_uTd_m-vMkbODvTH1-6gbFIAbUCo3sq77ET";
        private static string corpSecret = "";//"gtXlCYi2NHCGXG9R3Yc_VD9q3Gcujw39BV7U84nQKhyxs4OmpNyS_S5VSwS1YzjR";//
        private static string appTZGGID = "";//WXHelp.GetWXInfo("appTZGGID");//通知公告应用ID
        private static string appGRXXID = "";//WXHelp.GetWXInfo("appGRXXID");//个人消息ID
        public static string FileServerUrl = "";
        public static string FileServerUrlUpload = "";

        //public static string isUseWX = WXHelp.GetWXInfo("isUseWX");//是否使用企业号的开关
        public static string isUseWX = "N";//"Y";//是否使用企业号的开关

        public static string IMToken = "";
        public static string IMAesKey = "";

        static WXHelp()
        {
            DataTable dt = GetQYInfo();
            string strurl = dt.Rows[0]["WXUrl"].ToString();
            if (strurl.Substring(strurl.Length - 1, 1) == "/")
            {
                WXUrl = strurl;
            }
            else
            {
                WXUrl = strurl + "/";
            }

            corpId = dt.Rows[0]["corpId"].ToString();
            corpSecret = dt.Rows[0]["corpSecret"].ToString();
            appTZGGID = dt.Rows[0]["SystemGGId"].ToString();
            appGRXXID = dt.Rows[0]["MsgAppID"].ToString();
            isUseWX = dt.Rows[0]["isUseWX"].ToString();
            FileServerUrl = dt.Rows[0]["FileServerUrl"].ToString();
            if (FileServerUrl.Substring(FileServerUrl.Length - 1, 1) != "/")
            {
                FileServerUrl = FileServerUrl + "/";
            }
            FileServerUrlUpload = FileServerUrl + "fileupload?qycode=" + dt.Rows[0]["QYCode"].ToString();

            IMToken = dt.Rows[0]["Token"].ToString();
            IMAesKey = dt.Rows[0]["EncodingAESKey"].ToString();
        }


        public static string GetToken()
        {
            if (isUseWX == "Y")
            {
                AccessTokenResult Token = CommonApi.GetToken(WXHelp.corpId.Trim(), WXHelp.corpSecret.Trim());
                return Token.access_token;
            }
            else
            {
                return "";
            }
        }
        public static JsApiTicketResult GetTicket()
        {
            if (isUseWX == "Y")
            {
                JsApiTicketResult js = CommonApi.GetTicket(WXHelp.corpId, WXHelp.corpSecret);
                return js;
            }
            else
            {
                return null;

            }
        }

        public static void SendTH(Article MODEL, string flag, int ID, string strUserS = "@all")
        {
            thModel th = new thModel();
            th.MODEL = MODEL;
            th.FLAG = flag;
            th.ID = ID;
            th.UserS = string.IsNullOrEmpty(strUserS) ? "@all" : strUserS;
            th.isUseWX = isUseWX;

            System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(SendCommonMSG), th);
        }

        /// <summary>
        /// 发送通知消息
        /// </summary>
        /// <param name="MODEL"></param>
        /// <param name="flag"></param>
        /// <param name="ID"></param>
        /// <param name="strUserS"></param>
        private static void SendCommonMSG(object o)//Article MODEL, string flag, int ID, string strUserS = "@all")
        {
            try
            {
                thModel th = (thModel)o;
                if (th.isUseWX == "Y")
                {
                    string appid = appGRXXID;
                    switch (th.FLAG)
                    {
                        case "grxx"://个人消息
                            {
                                // th.MODEL.PicUrl = WXUrl + "MobileView/Images/HuoDong.png";
                                //th.MODEL.Url = WXUrl + "";
                            }
                            break;
                        case "qygg"://企业公告
                            {
                                if (th.MODEL.PicUrl=="")
                                {
                                    th.MODEL.PicUrl = WXUrl + "MobileView/Images/GGTitle.png";
                                }
                                th.MODEL.Url = WXUrl + "MobileView/UI/UI_COMMON.html?funcode=qygga_" + th.ID;
                                appid = appTZGGID;
                            }
                            break;
                        case "gzrb"://工作日报
                            {
                                //th.MODEL.PicUrl = WXUrl + "MobileView/Images/HuoDong.png";
                                th.MODEL.Url = WXUrl + "MobileView/UI/UI_COMMON.html?funcode=gzrbc_" + th.ID;

                            }
                            break;
                        case "hdbm"://活动报名
                            {
                                //th.MODEL.PicUrl = WXUrl + "MobileView/Images/HuoDong.png";
                                th.MODEL.Url = WXUrl + "MobileView/UI/UI_COMMON.html?funcode=hdbmc_" + th.ID;

                            }
                            break;
                        case "rctx"://任务待办
                            {
                                //th.MODEL.PicUrl = WXUrl + "MobileView/Images/HuoDong.png";
                                th.MODEL.Url = WXUrl + "MobileView/UI/UI_COMMON.html?funcode=dbsxd_" + th.ID;

                            }
                            break;
                        case "ccxj"://请假出差
                            {
                                //th.MODEL.PicUrl = WXUrl + "MobileView/Images/HuoDong.png";
                                th.MODEL.Url = WXUrl + "MobileView/UI/UI_COMMON.html?funcode=qjccc_" + th.ID;

                            }
                            break;
                        case "jfbx"://经费报销
                            {
                                //th.MODEL.PicUrl = WXUrl + "MobileView/Images/HuoDong.png";
                                th.MODEL.Url = WXUrl + "MobileView/UI/UI_COMMON.html?funcode=jfbxc_" + th.ID;

                            }
                            break;
                        case "lcsp"://流程审批
                            {
                                //th.MODEL.PicUrl = WXUrl + "MobileView/Images/HuoDong.png";
                                th.MODEL.Url = WXUrl + "MobileView/UI/UI_COMMON.html?funcode=lcspc_" + th.ID;

                            }
                            break;
                        case "zxzx"://在线咨询
                            {
                                //th.MODEL.PicUrl = WXUrl + "MobileView/Images/HuoDong.png";
                                th.MODEL.Url = WXUrl + "MobileView/UI/UI_COMMON.html?funcode=zxzxc_" + th.ID;

                            }
                            break;
                    }
                    //if (!string.IsNullOrEmpty(th.MODEL.Url))
                    //{
                    List<Article> Msgs = new List<Article>();
                    Msgs.Add(th.MODEL);
                    MassApi.SendNews(GetToken(), th.UserS.Replace(',', '|'), "", "", appid, Msgs);
                    //}
                    //MassApi.SendText(GetToken(), th.UserS.Replace(',', '|'), "", "", "40", "测试主页性应用");
                }
            }
            catch { }
        }
        public static string GetMsgLink(string type, string Id, int PIID)
        {
            string url = "";
            switch (type)
            {
                case "gzrb":
                    url = "/View/APPBaseView/APP_GZRZ_VIEW.html?ID=" + Id + "&pageType=view";
                    break;
                case "zxzx":
                    url = "/ViewV3/APPBaseView/APP_ANSWER.html?ID=" + Id + "&pageType=view";
                    break;
                default:
                    string strPara = PIID > 0 ? "&PIID=" + PIID : "";
                    url = "/ViewV3/APPBaseView/APP_ADD_WF.html?FormCode=" + type.ToUpper() + "&pageType=view&ID=" + Id + strPara;
                    break;
            }
            return url;
        }

        public static string GetWxLink(string type, string id)
        {
            string url = WXUrl;
            switch (type)
            {
                case "qygg"://企业公告
                    {
                        url += "MobileView/UI/UI_COMMON.html?funcode=qygga_" + id;
                    }
                    break;
                case "gzrb"://工作日报
                    {
                        url += "MobileView/UI/UI_COMMON.html?funcode=gzrbc_" + id;

                    }
                    break;
                case "hdbm"://活动报名
                    {
                        url += "MobileView/UI/UI_COMMON.html?funcode=hdbmc_" + id;

                    }
                    break;
                case "rctx"://任务待办
                    {
                        url += "MobileView/UI/UI_COMMON.html?funcode=dbsxd_" + id;

                    }
                    break;
                case "ccxj"://请假出差
                    {
                        url += "MobileView/UI/UI_COMMON.html?funcode=qjccc_" + id;

                    }
                    break;
                case "jfbx"://经费报销
                    {
                        url += "MobileView/UI/UI_COMMON.html?funcode=jfbxc_" + id;

                    }
                    break;
                case "lcsp"://流程审批
                    {
                        //th.MODEL.PicUrl = WXUrl + "MobileView/Images/HuoDong.png";
                        url += "MobileView/UI/UI_COMMON.html?funcode=lcspc_" + id;

                    }
                    break;
                case "zxzx"://在线咨询
                    {
                        //th.MODEL.PicUrl = WXUrl + "MobileView/Images/HuoDong.png";
                        url += "MobileView/UI/UI_COMMON.html?funcode=zxzxc_" + id;

                    }
                    break;
            }


            return url;
        }


        public void SendWXMsg(Article MODEL, string strAPPID, string strUserS = "@all")
        {
            if (isUseWX == "Y")
            {
                List<Article> Msgs = new List<Article>();
                Msgs.Add(MODEL);
                MassApi.SendNews(GetToken(), strUserS, "", "", strAPPID, Msgs);
            }
        }
        public void SendWXRText(string MsgText, string strAPPID, string strUserS = "@all")
        {
            if (isUseWX == "Y")
            {

                MassApi.SendText(GetToken(), strUserS, "", "", strAPPID, MsgText);
            }
        }
        public static string GetCodeURL(string Redurl)
        {
            string url = "";
            if (isUseWX == "Y")
            {
                url = OAuth2Api.GetCode(WXHelp.corpId, Redurl, "");
            }
            return url;
        }
        public static string GetUserDataByCode(string strCode)
        {
            string UserCode = "";

            try
            {
                if (isUseWX == "Y")
                {

                    GetUserInfoResult OBJ = OAuth2Api.GetUserId(GetToken(), strCode, "0");
                    UserCode = OBJ.UserId;

                }
            }
            catch (Exception EX)
            {
                new JH_Auth_LogB().Insert(new JH_Auth_Log() { CRDate = DateTime.Now, LogContent = "获取用户代码GetUserDataByCode" + EX.Message.ToString() });

            }

            return UserCode;
        }

        public static class BranchMangner
        {




            public static void WX_CreateBranch(JH_Auth_Branch Model)
            {
                if (isUseWX == "Y")
                {
                    MailListApi.CreateDepartment(WXHelp.GetToken(), Model.DeptName, Model.DeptRoot, Model.DeptShort, Model.DeptCode);
                }
            }

            public static QyJsonResult WX_UpdateBranch(JH_Auth_Branch Model)
            {
                QyJsonResult Ret = new QyJsonResult();
                if (isUseWX == "Y")
                {
                    Ret = MailListApi.UpdateDepartment(WXHelp.GetToken(), Model.DeptCode.ToString(), Model.DeptName, Model.DeptRoot, Model.DeptShort);
                }
                return Ret;
            }

            public static QyJsonResult WX_DelBranch(string strDeptCode)
            {
                QyJsonResult Ret = new QyJsonResult();
                if (isUseWX == "Y")
                {
                    Ret = MailListApi.DeleteDepartment(WXHelp.GetToken(), strDeptCode);
                }
                return Ret;
            }


            public static QyJsonResult WX_CreateUser(JH_Auth_User Model)
            {
                QyJsonResult Ret = new QyJsonResult();
                if (isUseWX == "Y")
                {
                    int[] Branch = { Model.BranchCode };
                    Ret = MailListApi.CreateMember(WXHelp.GetToken(), Model.UserName, Model.UserRealName, Branch, Model.zhiwu, Model.mobphone, Model.mailbox, Model.weixinnum);
                }
                return Ret;
            }
            /// <summary>
            /// 更新用户包括状态
            /// </summary>
            /// <param name="Model"></param>
            /// <returns></returns>
            public static QyJsonResult WX_UpdateUser(JH_Auth_User Model)
            {
                //  CommonHelp.WriteLog("Token:" + WXHelp.GetToken() + " UserName" + Model.UserName + "UserRealName:" + Model.UserRealName + "Branch:" + Model.BranchCode + "zhiwu:" + Model.zhiwu + "mobphone：" + Model.mobphone + "mailbox：" + Model.mailbox + "weixinNum：" + Model.weixinnum);
                QyJsonResult Ret = new QyJsonResult();
                if (isUseWX == "Y")
                {
                    int[] Branch = { Model.BranchCode };
                    Ret = MailListApi.UpdateMember(WXHelp.GetToken(), Model.UserName, Model.UserRealName, Branch, Model.zhiwu, Model.mobphone, Model.mailbox, Model.weixinnum, Model.IsUse == "Y" ? 1 : 0);
                }
                return Ret;
            }
           
            public static QyJsonResult WX_DelUser(string strUserName)
            {
                QyJsonResult Ret = new QyJsonResult();
                if (isUseWX == "Y")
                {
                    Ret = MailListApi.DeleteMember(WXHelp.GetToken(), strUserName);
                }
                return Ret;
            }

        }



        public static string GetWXInfo(string strKey)
        {
            try
            {
                //string strPath = System.Web.HttpRuntime.AppDomainAppPath + "View\\SiteSet\\SiteSet.json";
                //StreamReader sr = new StreamReader(strPath, Encoding.Default);
                //string strJson = sr.ReadToEnd();
                //JObject jo = JObject.Parse(strJson);
                //var data = jo.Properties().Where(item => item.Name.ToString() == strKey).FirstOrDefault();
                //sr.Close();
                //return data.Value.ToString();
                return "";
            }
            catch (Exception)
            {

                throw;
            }


        }

        public static DataTable GetQYInfo()
        {
            try
            {
                return new JH_Auth_QYB().GetDTByCommand("select * from JH_Auth_QY");
            }
            catch (Exception)
            {

                throw;
            }

        }

        public static string GetMediaFile(string mediaId)
        {
            string path = HttpContext.Current.Server.MapPath("\\temp\\");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string mdfile = path + Guid.NewGuid().ToString() + ".jpg";
            FileStream fs = new FileStream(mdfile, FileMode.Create);

            MediaApi.Get(GetToken(), mediaId, fs);
            fs.Close();
            return mdfile;
        }
    }

    public class thModel
    {
        public Article MODEL { get; set; }
        public string FLAG { get; set; }
        public int ID { get; set; }
        public string UserS { get; set; }
        public string isUseWX { get; set; }
    }
}